package com.why.client;

import com.why.message.RpcRequest;
import com.why.message.RpcResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @program: why-rpc-framework
 * @description:
 * @author: @why
 * @create: 2021-03-15 17:16
 **/
@Slf4j
public class RpcClient {
    private int port;
    private String host;

    public RpcClient(int port, String host) {
        this.port = port;
        this.host = host;
    }


    public Object sendRequest(RpcRequest request) {

        try {
            //创建socket连接
            Socket socket = new Socket(host, port);
            //得到输入输出流
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());

            //将请求数据写出去
            outputStream.writeObject(request);
            outputStream.flush();
            //读取响应信息
            RpcResponse response = (RpcResponse) inputStream.readObject();

            log.info("成功接收请求{}", response);
            return response.getData();

        } catch (IOException | ClassNotFoundException e) {
            log.info("连接失败");
            e.printStackTrace();
        }
        return null;

    }
}